<template>
  <a-modal class="common-modal" :title="$t('hangManage.addWeekTargetYield')" :footer="null" :width="720" :visible="visible" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-form :model="formState" class="common-modal-content operate-week" ref="formRef" :rules="rule">
      <div class="space-between pr-20 align-baseline">
        <div class="blue-line">{{ $t('hangManage.everyWeekTargetYield') }}</div>
        <div>
          <a-form-item :rules="{ required: true, message: $t('other.selectDate') }" name="timeRange">
            <a-range-picker v-model:value="formState.timeRange" value-format="YYYY-MM-DD" />
          </a-form-item>
        </div>
      </div>
      <div class="flex">
        <div>
          <a-tabs :activeKey="activeKey" tab-position="left" :style="{ height: '400px' }" @tabClick="onTabChange">
            <a-tab-pane v-for="item in weekDay" :key="item.value" :tab="item.label"></a-tab-pane>
          </a-tabs>
        </div>
        <div class="pr-20" :key="activeKey">
          <a-form :model="obj[activeKey]" ref="timeRef" layout="horizontal">
            <a-table rowKey="index" bordered size="small" :dataSource="obj[activeKey]" :columns="addDayColumns" :pagination="false" class="form-table mb-20" :scroll="{y: 400}">
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.key === 'timeRange'">
                  <a-form-item :name="[index, 'timeRange']" :rules="[{ validator: (_rule, value)=> validateTime(_rule, value, record.timeRange, index), trigger: 'change'} ]">
                    <a-time-range-picker v-model:value="record.timeRange" format="HH:mm" value-format="HH:mm" />
                  </a-form-item>
                </template>
                <template v-if="column.key === 'targetYield'">
                  <a-form-item :name="[index, 'targetYield']">
                    <a-input-number v-model:value="record.targetYield" :min="0" />
                  </a-form-item>
                </template>
                <template v-else-if="column.key === 'operate'">
                  <span class="table-operate-container">
                    <a-button type="link" class="primary-link" @click="handleAdd">{{ $t('common.addNew') }}</a-button>
                    <a-divider type="vertical" />
                    <a-button type="link" class="warning-link" :disabled="obj[activeKey].length === 1" @click="handleDelete(record.id)">{{ $t('common.del') }}</a-button>
                  </span>
                </template>
              </template>
            </a-table>
          </a-form>
        </div>
      </div>
    </a-form>

    <div class="common-modal-footer mt-10">
      <a-button @click="handleCancel" class="cancel">{{ $t('common.cancel') }}</a-button>
      <a-button @click="handleOk" type="primary" class="confirm">{{ $t('common.ok') }}</a-button>
    </div>
    <!-- </a-spin> -->
  </a-modal>
</template>

<script setup>
import { nextTick, ref } from 'vue'
import { cloneDeep } from 'lodash'
import { weekDay } from './config'
import { addDayColumns } from './config'
import axios from '@/utils/request'
import { message } from 'ant-design-vue'
import i18n from '@/locales/index'

const { t } = i18n.global
const emits = defineEmits(['ok'])
let isEdit = ref(false)
let visible = ref(false)
let confirmLoading = ref(false)
let recordInfo = ref({})
let formState = ref({})
const formRef = ref()
let activeKey = ref('2')
const timeRef = ref()
let obj = ref({})
let rule = []
const initModalData = () => {
  activeKey.value = '2';
  weekDay.forEach(i => {
    obj.value[i.value] = [{ timeRange: [], targetYield: 0, id: Math.random() }]
  })
}
const open = async (record, edit) => {
  isEdit.value = edit
  initModalData(record)
  visible.value = true
  await nextTick()
  formState.value = cloneDeep(recordInfo.value)
  formRef.value.resetFields()
}
const onTabChange = async (value) => {
  try {
    await timeRef.value.validateFields()
    activeKey.value = value
  } catch {
    console.log('err');
  }
}
const handleAdd = () => {
  obj.value[activeKey.value].push({ timeRange: [], targetYield: 0, id: Math.random() })
}
const handleDelete = (id) => {
  obj.value[activeKey.value] = obj.value[activeKey.value].filter(item => item.id !== id)
}
const validateTime = async (_rule, value, record, index) => {
  if (!value) {
    return Promise.resolve()
  } else {
    let choosedTimeList = []
    obj.value[activeKey.value].forEach((el, i) => {
      if (i != index) {
        if (el.timeRange.length) choosedTimeList.push(el.timeRange)
      }
    })
    let flag = false
    choosedTimeList.forEach(i => {
      if (!(value[1] <= i[0] || value[0] >= i[1])) flag = true
    })
    if (!flag) {
      return Promise.resolve()
    } else {
      return Promise.reject(t('other.dateUsed'))
    }
  }
}
const getParams = () => {
  console.log(formState.value);
  let { timeRange } = formState.value
  let params = {
    produceStartDate: timeRange[0],
    produceEndDate: timeRange[1],
  }
  let data = obj.value
  let ary = []
  Object.keys(data).forEach(i => {
    let obj = { weekday: i }
    obj.targetDetailList = data[i].filter(el => el.quantity || (el.timeRange && el.timeRange.length)).map(el => {
      return {
        endTime: el.timeRange[1],
        startTime: el.timeRange[0],
        quantity: el.targetYield
      }
    })
    if (obj.targetDetailList.length) ary.push(obj)
  })
  params.weekDayList = ary

  return params
}
const handleOk = async () => {
  try {
    await formRef.value.validateFields()
    await timeRef.value.validateFields()
    confirmLoading.value = true
    let params = getParams()
    const res = await axios.postAction('/api/hanger/yield-target/save-by-week', params)
    if (res.success) {
      message.success(res.msg || t('common.doSuccess'))
      handleCancel()
      emits('ok')
    }
  } catch (err) {
    confirmLoading.value = false
  }
}
const handleCancel = () => {
  visible.value = false
  confirmLoading.value = false
  formState.value = {}
  formRef.value.resetFields()
}

defineExpose({
  open
})
</script>
